{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Mnist 数据集\n",
    "整个数据集包括60000张训练图片，10000张测试图片。\n",
    "每张图片为一个28x28的灰度图片。每个像素的数据类型为uint8，取值从0（背景）到255（前景）。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 导入必要的模块"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 49,
   "metadata": {},
   "outputs": [],
   "source": [
    "\"\"\"A very simple MNIST classifier.\n",
    "See extensive documentation at\n",
    "https://www.tensorflow.org/get_started/mnist/beginners\n",
    "\"\"\"\n",
    "from __future__ import absolute_import\n",
    "from __future__ import division\n",
    "from __future__ import print_function\n",
    "\n",
    "import argparse\n",
    "import sys\n",
    "\n",
    "from tensorflow.examples.tutorials.mnist import input_data\n",
    "\n",
    "import tensorflow as tf"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 50,
   "metadata": {},
   "outputs": [],
   "source": [
    "def weight_variable(shape):\n",
    "  # Outputs random values from a truncated normal distribution(default, mean=0.0)\n",
    "  initial = tf.truncated_normal(shape, stddev=0.1) \n",
    "  return tf.Variable(initial)\n",
    "\n",
    "def bias_variable(shape):\n",
    "  initial = tf.constant(0.1, shape=shape)\n",
    "  return tf.Variable(initial)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 定义函数实现卷积和池化"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 51,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 定义函数实现卷积和池化\n",
    "# tf.nn.conv2d(\n",
    "#     input,\n",
    "#     filter,\n",
    "#     strides,\n",
    "#     padding,\n",
    "#     use_cudnn_on_gpu=True,\n",
    "#     data_format='NHWC',\n",
    "#     dilations=[1, 1, 1, 1],\n",
    "#     name=None\n",
    "# )\n",
    "# Computes a 2-D convolution given 4-D input and filter tensors.\n",
    "# Given an input tensor of shape [batch, in_height, in_width, in_channels] \n",
    "# and a filter / kernel tensor of shape [filter_height, filter_width, in_channels, out_channels]\n",
    "def conv2d(x, W):\n",
    "  return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')\n",
    "\n",
    "# tf.nn.max_pool(\n",
    "#     value,\n",
    "#     ksize,\n",
    "#     strides,\n",
    "#     padding,\n",
    "#     data_format='NHWC',\n",
    "#     name=None\n",
    "# )\n",
    "# value: A 4-D Tensor of the format specified by data_format.\n",
    "# ksize: A 1-D int Tensor of 4 elements. The size of the window for each dimension of the input tensor.\n",
    "# strides: A 1-D int Tensor of 4 elements. The stride of the sliding window for each dimension of the input tensor.\n",
    "# padding: A string, either 'VALID' or 'SAME'. \n",
    "# data_format: A string. 'NHWC', 'NCHW' and 'NCHW_VECT_C' are supported.\n",
    "# name: Optional name for the operation.\n",
    "def max_pool_2x2(x):\n",
    "  return tf.nn.max_pool(x, ksize=[1, 2, 2, 1],\n",
    "                        strides=[1, 2, 2, 1], padding='VALID')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 52,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Extracting /tmp/tensorflow/mnist/input_data\\train-images-idx3-ubyte.gz\n",
      "Extracting /tmp/tensorflow/mnist/input_data\\train-labels-idx1-ubyte.gz\n",
      "Extracting /tmp/tensorflow/mnist/input_data\\t10k-images-idx3-ubyte.gz\n",
      "Extracting /tmp/tensorflow/mnist/input_data\\t10k-labels-idx1-ubyte.gz\n"
     ]
    }
   ],
   "source": [
    "# Import data\n",
    "data_dir = '/tmp/tensorflow/mnist/input_data'\n",
    "mnist = input_data.read_data_sets(data_dir, one_hot=True)\n",
    "# Define loss and optimizer\n",
    "x = tf.placeholder(tf.float32, [None, 784])\n",
    "y_ = tf.placeholder(tf.float32, [None, 10])\n",
    "learning_rate = tf.placeholder(tf.float32)\n",
    "\n",
    "with tf.name_scope('reshape'):\n",
    "  # 定义输入数据 number, height, width, channel\n",
    "  # 四阶张量，-1表示暂定，依次是数据条数、高度、宽度、channels(在保证后三个维度的条件下自动计算第一个维度)\n",
    "  x_image = tf.reshape(x, [-1, 28, 28, 1])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 第一层卷积和池化\n",
    "第一层卷积的kernel size = 5 X 5 X 1\n",
    "filter数量：#filters = 32\n",
    "步长stride = 1\n",
    "padding采用same方式"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 53,
   "metadata": {},
   "outputs": [],
   "source": [
    "W_conv1 = weight_variable([5, 5, 1, 32])\n",
    "b_conv1 = bias_variable([32])\n",
    "h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)\n",
    "h_pool1 = max_pool_2x2(h_conv1)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 第二层卷积和池化\n",
    "第二层卷积的kernel size = 5 X 5 X 32\n",
    "filter数量：#filters = 64\n",
    "步长stride = 1\n",
    "padding采用same方式"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 54,
   "metadata": {},
   "outputs": [],
   "source": [
    "W_conv2 = weight_variable([5, 5, 32, 64])\n",
    "b_conv2 = bias_variable([64])\n",
    "\n",
    "h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)\n",
    "h_pool2 = max_pool_2x2(h_conv2)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 密集连接层"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 55,
   "metadata": {},
   "outputs": [],
   "source": [
    "W_fc1 = weight_variable([7 * 7 * 64, 1024])\n",
    "b_fc1 = bias_variable([1024])\n",
    "\n",
    "h_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*64])\n",
    "h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Dropout"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 56,
   "metadata": {},
   "outputs": [],
   "source": [
    "# keep_prob = tf.placeholder(\"float\")\n",
    "keep_prob = tf.placeholder(tf.float32)\n",
    "h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 输出层"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 57,
   "metadata": {},
   "outputs": [],
   "source": [
    "W_fc2 = weight_variable([1024, 10])\n",
    "b_fc2 = bias_variable([10])\n",
    "\n",
    "# y_conv=tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2)\n",
    "y = tf.matmul(h_fc1_drop, W_fc2) + b_fc2"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 训练和评估模型\n",
    "使用学习率衰减来加速算法收敛"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 58,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "step 100, entropy loss: 1.129331, l2_loss: 50776.304688, total loss: 4.683673\n",
      "0.85\n",
      "step 200, entropy loss: 0.608932, l2_loss: 50769.441406, total loss: 4.162793\n",
      "0.91\n",
      "step 300, entropy loss: 0.552382, l2_loss: 50762.535156, total loss: 4.105760\n",
      "0.95\n",
      "step 400, entropy loss: 0.387689, l2_loss: 50755.589844, total loss: 3.940580\n",
      "0.97\n",
      "step 500, entropy loss: 0.324219, l2_loss: 50748.601562, total loss: 3.876621\n",
      "0.94\n",
      "step 600, entropy loss: 0.189656, l2_loss: 50741.621094, total loss: 3.741570\n",
      "0.96\n",
      "step 700, entropy loss: 0.320524, l2_loss: 50734.628906, total loss: 3.871948\n",
      "0.95\n",
      "step 800, entropy loss: 0.363883, l2_loss: 50727.574219, total loss: 3.914813\n",
      "0.95\n",
      "step 900, entropy loss: 0.264362, l2_loss: 50720.605469, total loss: 3.814805\n",
      "0.97\n",
      "step 1000, entropy loss: 0.095895, l2_loss: 50713.585938, total loss: 3.645846\n",
      "0.97\n",
      "0.9617\n",
      "step 1100, entropy loss: 0.206263, l2_loss: 50706.562500, total loss: 3.755723\n",
      "0.98\n",
      "step 1200, entropy loss: 0.406343, l2_loss: 50699.554688, total loss: 3.955312\n",
      "0.95\n",
      "step 1300, entropy loss: 0.226645, l2_loss: 50692.515625, total loss: 3.775121\n",
      "0.96\n",
      "step 1400, entropy loss: 0.148028, l2_loss: 50685.531250, total loss: 3.696015\n",
      "0.99\n",
      "step 1500, entropy loss: 0.151783, l2_loss: 50678.503906, total loss: 3.699278\n",
      "0.97\n",
      "step 1600, entropy loss: 0.126330, l2_loss: 50671.453125, total loss: 3.673331\n",
      "0.99\n",
      "step 1700, entropy loss: 0.093960, l2_loss: 50664.437500, total loss: 3.640471\n",
      "1.0\n",
      "step 1800, entropy loss: 0.144489, l2_loss: 50657.421875, total loss: 3.690509\n",
      "0.96\n",
      "step 1900, entropy loss: 0.187828, l2_loss: 50650.390625, total loss: 3.733356\n",
      "0.97\n",
      "step 2000, entropy loss: 0.119432, l2_loss: 50643.335938, total loss: 3.664466\n",
      "0.98\n",
      "0.9738\n",
      "step 2100, entropy loss: 0.217976, l2_loss: 50636.324219, total loss: 3.762519\n",
      "0.96\n",
      "step 2200, entropy loss: 0.104102, l2_loss: 50629.289062, total loss: 3.648152\n",
      "0.99\n",
      "step 2300, entropy loss: 0.196727, l2_loss: 50622.257812, total loss: 3.740285\n",
      "0.98\n",
      "step 2400, entropy loss: 0.134648, l2_loss: 50615.222656, total loss: 3.677713\n",
      "0.97\n",
      "step 2500, entropy loss: 0.139863, l2_loss: 50608.187500, total loss: 3.682437\n",
      "0.97\n",
      "step 2600, entropy loss: 0.095888, l2_loss: 50601.164062, total loss: 3.637969\n",
      "0.98\n",
      "step 2700, entropy loss: 0.093639, l2_loss: 50594.140625, total loss: 3.635229\n",
      "0.98\n",
      "step 2800, entropy loss: 0.104870, l2_loss: 50587.132812, total loss: 3.645969\n",
      "0.98\n",
      "step 2900, entropy loss: 0.143009, l2_loss: 50580.089844, total loss: 3.683615\n",
      "0.99\n",
      "step 3000, entropy loss: 0.086233, l2_loss: 50573.054688, total loss: 3.626347\n",
      "0.98\n",
      "0.9784\n"
     ]
    }
   ],
   "source": [
    "# Fully connected layer 1 -- after 2 round of downsampling, our 28x28 image\n",
    "# is down to 7x7x64 feature maps -- maps this to 1024 features.\n",
    "\n",
    "# with tf.name_scope('fc1'):\n",
    "#   # global average pooling/全局平均池化 f = height X weight 7 X 7 X 64 ------> 1 X 1 X 64\n",
    "#   h_pool2_flat = tf.contrib.slim.avg_pool2d(h_pool2, h_pool2.shape[1:3],\n",
    "#                         stride=[1, 1], padding='VALID')\n",
    "#   h_fc1 = tf.contrib.slim.conv2d(h_pool2_flat, 1024, [1,1], activation_fn=tf.nn.relu)\n",
    "\n",
    "# Dropout - controls the complexity of the model, prevents co-adaptation of\n",
    "# features.\n",
    "\n",
    "# with tf.name_scope('dropout'):\n",
    "#   keep_prob = tf.placeholder(tf.float32)\n",
    "#   h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)\n",
    "\n",
    "# Map the 1024 features to 10 classes, one for each digit\n",
    "\n",
    "# with tf.name_scope('fc2'):\n",
    "#   y = tf.squeeze(tf.contrib.slim.conv2d(h_fc1_drop, 10, [1,1], activation_fn=None))\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "# The raw formulation of cross-entropy,\n",
    "#\n",
    "#   tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(tf.nn.softmax(y)),\n",
    "#                                 reduction_indices=[1]))\n",
    "#\n",
    "# can be numerically unstable.\n",
    "#\n",
    "# So here we use tf.nn.softmax_cross_entropy_with_logits on the raw\n",
    "# outputs of 'y', and then average across the batch.\n",
    "\n",
    "# 学习率衰减\n",
    "# exponetial learning rate decay\n",
    "epoch_steps = tf.to_int64(tf.div(60000, tf.shape(x)[0]))  # 1 epoch = 600 steps\n",
    "global_step = tf.train.get_or_create_global_step()\n",
    "# 1.单斜杠（/）表示除法，且不管除数和被除数是不是整数，最后结果都是float类型。\n",
    "# 2.双斜杠（//）表示地板除，即先做除法（/），然后向下取整（floor）。\n",
    "# 至少有一方是float型时，结果为float型；两个数都是int型时，结果为int型。\n",
    "current_epoch = global_step//epoch_steps\n",
    "decay_times = current_epoch \n",
    "current_learning_rate = tf.multiply(learning_rate, \n",
    "                                    tf.pow(0.575, tf.to_float(decay_times)))\n",
    "\n",
    "cross_entropy = tf.reduce_mean(\n",
    "    tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y))\n",
    "\n",
    "l2_loss = tf.add_n( [tf.nn.l2_loss(w) for w in tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES)] )\n",
    "total_loss = cross_entropy + 7e-5*l2_loss\n",
    "train_step = tf.train.GradientDescentOptimizer(current_learning_rate).minimize(total_loss)\n",
    "\n",
    "sess = tf.Session()\n",
    "init_op = tf.global_variables_initializer()\n",
    "sess.run(init_op)\n",
    "# Train\n",
    "for step in range(3000):\n",
    "  batch_xs, batch_ys = mnist.train.next_batch(100)\n",
    "  lr = 0.01\n",
    "  _, loss, l2_loss_value, total_loss_value, current_lr_value = sess.run(\n",
    "               [train_step, cross_entropy, l2_loss, total_loss, \n",
    "                current_learning_rate], \n",
    "               feed_dict={x: batch_xs, y_: batch_ys, learning_rate:lr, keep_prob:0.5})\n",
    "  \n",
    "  if (step+1) % 100 == 0:\n",
    "    print('step %d, entropy loss: %f, l2_loss: %f, total loss: %f' % \n",
    "            (step+1, loss, l2_loss_value, total_loss_value))\n",
    "    # Test trained model\n",
    "    correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))\n",
    "    accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\n",
    "    print(sess.run(accuracy, feed_dict={x: batch_xs, y_: batch_ys, keep_prob:1.0}))\n",
    "  if (step+1) % 1000 == 0:\n",
    "    print(sess.run(accuracy, feed_dict={x: mnist.test.images,\n",
    "                                    y_: mnist.test.labels, keep_prob:1.0}))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    ""
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3.0
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}